package com.cloudcc.mobile.view.dynamic;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cloudcc.cloudframe.net.ErrorInfo;
import com.cloudcc.cloudframe.net.ResultCallBack;
import com.cloudcc.cloudframe.util.DensityUtils;
import com.cloudcc.cloudframe.util.ListUtils;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.adapter.RelevantChatAdatper;
import com.cloudcc.mobile.adapter.RelevantPopAdapter;
import com.cloudcc.mobile.dao.impl.ChatterEngineImpl;
import com.cloudcc.mobile.entity.AddImageInfo;
import com.cloudcc.mobile.entity.chatter.ChatterEventType;
import com.cloudcc.mobile.manager.CacheManager;
import com.cloudcc.mobile.network.QianDaoNewWork;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.view.activity.EditorActivity;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.cloudcc.mobile.view.dynamic.relevant.RelevantChatFragment;
import com.cloudcc.mobile.view.dynamic.relevant.RelevantWebFragment;

public class RelevantActivtiy extends BaseActivity {

	public static LinearLayout relevant_bottom;
	public static ViewPager viewPager;
	public static ViewGroup group;
	private ImageView[] imageViews;
	private ImageView imageView;
	private RelevantChatAdatper adapter;
	private RelevantPopAdapter adapter2;
	private TextView textView;
	private TextView[] textViews;
	private String id;
	private ImageView leixing;
	private ImageView fasong;
	private EditText context_text;
	private RelativeLayout dibu;
	private ListView listView;
	private PopupWindow popupWindow;
	private MyReceivers receiver;
	public String mUrl = StringUtils.EMPTY;

	@Override
	public void init(Bundle savedInstanceState) {
		super.init(savedInstanceState);
		id = getIntent().getStringExtra("web");
		mUrl = getIntent().getStringExtra("web.url");
		setView();
		addListener();
		initChatterEventTypes();
	}
	
	@Override
	protected void onNewIntent(Intent intent) {
		finish();
		startActivity(intent);
	}

	private void addListener() {
		fasong.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				sendRelevantChat();
			}
		});
		leixing.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				showPopup();
			}
		});
		viewPager.setOnPageChangeListener(new OnPageChangeListener() {
			@Override
			public void onPageSelected(int position) {
				for (int i = 0; i < imageViews.length; i++) {
					imageViews[position]
							.setBackgroundResource(R.drawable.ball_red);
					if (position != i) {
						imageViews[i]
								.setBackgroundResource(R.drawable.ball_grey);
					}
				}
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
			}
		});

	}

	protected void sendRelevantChat() {
		String name = context_text.getText().toString().trim();
		if (name.equals("")) {
			Tools.showInfo(mContext, "内容不能为空！");
			return;
		}
		List<AddImageInfo> list = new ArrayList<AddImageInfo>();
		QianDaoNewWork qiandao = new QianDaoNewWork(mContext, Tools.getNum());
		qiandao.QiaoDaoChat(null, id, "汇报记录:【" + AppContext.relevantName + "】",
				list, name, "1", "汇报记录");
		context_text.setText("");
	}

	/**
	 * 初始化 事件类型
	 */
	private void initChatterEventTypes() {
		mTypes = CacheManager.getInstance().getEventTypes();
		refreshEventTypes();
	}

	/**
	 * 刷新事件类型了列表
	 */
	private void refreshEventTypes() {
		new ChatterEngineImpl()
				.getChatterEventTypes(new ResultCallBack<List<ChatterEventType>>() {

					@Override
					public void onSuccess(List<ChatterEventType> types) {
						mTypes = types;
						CacheManager.getInstance().cacheEventTypes(types);
					}

					@Override
					public void onFailure(ErrorInfo error) {
						mTypes = CacheManager.getInstance().getEventTypes();
					}
				});
	}

	private List<ChatterEventType> mTypes;

	private List<String> fillEventTypes() {
		List<String> list = new ArrayList<String>();
		if (ListUtils.isEmpty(mTypes)) {
			list.add("汇报记录");
			list.add("发讨论帖");
			list.add("签到拜访");
			list.add("记录电话");
			list.add("记录短信");
			list.add("记录邮件");
			list.add("写个备注");
			return list;
		}
		for (ChatterEventType type : mTypes) {
			if (StringUtils.isBlank(type.key)) {
				continue;
			}
			list.add(type.key);
		}
		return list;
	}

	protected void showPopup() {
		if (popupWindow == null) {
			View view = LayoutInflater.from(mContext).inflate(
					R.layout.relevant_pop, null);
			listView = (ListView) view.findViewById(R.id.relevant_popup);
			listView.setScrollbarFadingEnabled(true);
			List<String> list = fillEventTypes();
			adapter2 = new RelevantPopAdapter(mContext, list);
			listView.setAdapter(adapter2);
			popupWindow = new PopupWindow(view,
					(int) DensityUtils.getScreenWidth(this) * 2 / 5,
					(int) DensityUtils.getScreenHeight(this) / 3);
		}
		popupWindow.setFocusable(true);
		popupWindow.setOutsideTouchable(true);
		// 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		popupWindow.showAsDropDown(dibu, 5, 3);
		listView.setOnItemClickListener(new OnItemClickListener() {
			private String relevantName;
			private String key;
			private String reuevantType;

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (popupWindow.isShowing()) {
					popupWindow.dismiss();
				}
				String name = adapter2.getItem(arg2);
				relevantName = name+"【" + AppContext.relevantName + "】";
				reuevantType = name;
				key = "1";
				Intent intent = new Intent(mContext, EditorActivity.class);
				intent.putExtra("urlId", id);
				intent.putExtra("key", key);
				intent.putExtra("CustomerActivity", relevantName);
				intent.putExtra("reuevantType", reuevantType);
				intent.putExtra("name", name);
				intent.putExtra("from", "web");
				startActivity(intent);

			}
		});
	}

	@SuppressLint("NewApi")
	private void setView() {
		registerReceiver();
		viewPager = (ViewPager) findViewById(R.id.viewpager);
		viewPager.setOffscreenPageLimit(0);
		relevant_bottom = (LinearLayout) findViewById(R.id.relevant_bottom);
		group = (ViewGroup) findViewById(R.id.viewGroup);
		leixing = (ImageView) findViewById(R.id.leixing);
		dibu = (RelativeLayout) findViewById(R.id.relevent_dibu);
		fasong = (ImageView) findViewById(R.id.relevant_fasong);
		context_text = (EditText) findViewById(R.id.context_text);
		ArrayList<Fragment> views = new ArrayList<Fragment>();
		RelevantChatFragment chat = new RelevantChatFragment();
		RelevantWebFragment web = new RelevantWebFragment();
		Bundle args = new Bundle();
		args.putString("url", mUrl);
		web.setArguments(args);
		views.add(web);
		views.add(chat);
		imageViews = new ImageView[2];
		textViews = new TextView[2];
		for (int i = 0; i < 2; i++) {
			imageView = new ImageView(this);
			textView = new TextView(this);
			textView.setWidth(10);
			imageView.setPadding(5, 5, 5, 5);
			imageViews[i] = imageView;
			textViews[i] = textView;
			if (i == 0) {
				imageViews[i].setBackgroundResource(R.drawable.ball_red);
			} else {
				imageViews[i].setBackgroundResource(R.drawable.ball_grey);
			}
			group.addView(textViews[i]);
			group.addView(imageViews[i]);
		}
		adapter = new RelevantChatAdatper(getSupportFragmentManager(), views);
		viewPager.setAdapter(adapter);

	}

	private void registerReceiver() {
		receiver = new MyReceivers();
		IntentFilter filter = new IntentFilter();
		filter.addAction(AppContext.RECORD_ID_CHANGED_SHUAXIN);
		registerReceiver(receiver, filter);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(receiver);
	}

	class MyReceivers extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(AppContext.RECORD_ID_CHANGED_SHUAXIN)) {
				id = AppContext.record_id;
			}
		}
	}

	@Override
	public int getLayoutId() {
		return R.layout.relevant;
	}
}
